package com.queue.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized结合Object上的wait和notify方法可以实现线程间的等待通知机制
 * ReentrantLock结合Condition接口同样可以实现这个功能。
 *
 * @author: chenhs
 * @date: Created in 10:48 2019/10/11
 **/
public class ConditionTest {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();


    public static void main(String[] args) throws InterruptedException {
        lock.lock();
        new Thread(new SignalThread()).start();
        System.out.println("主线程等待通知！");

        try {
            /**
             *  await()将释放锁,并且在该Condition上等待,类似Synchronized的wait()
             */
            condition.await();
        } finally {
            lock.unlock();
        }
        System.out.println("主线程恢复运行！");
    }


    static class SignalThread implements Runnable {

        @Override
        public void run() {
            lock.lock();
            try {
                /**
                 * 直到有其他线程调用Condition的signal()方法唤醒线程。
                 * 类似Synchronized的notify()
                 */
                condition.signal();
                System.out.println("子线程通知！");
            } finally {
                lock.unlock();
            }
        }
    }


}
